<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="../StaticFiles/element-ui/element-ui.css">
  <link rel="stylesheet" href="../StaticFiles/nprogress/nprogress.min.css">
  <link rel="stylesheet" href="../styles/vue-page-common.css">
  <script src="../Scripts/vue.min.js"></script>
  <script src="../StaticFiles/element-ui/element-ui.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <script src="../Scripts/xlsx.full.min.js"></script>
  <script src="../Scripts/crypto-js.js"></script>
  <script src="../Scripts/secret.js"></script>
  <title>订单分类导入</title>
</head>

<body>
  <div id="app" v-cloak>
    <!-- 报表标题 -->
    <vue2-report-header :title="factoryname+'订单分类导入'"></vue2-report-header>
    <div style="padding: 10px;">
      <!-- 查询条件区 -->
      <el-form :inline="true" :model="queryInfo" ref="queryInfoRef" :label-position="'left'" :disabled="formDisable">
        <el-form-item prop='productname' label="零件图号:">
          <el-autocomplete v-model.trim="queryInfo.productname" placeholder="请输入零件图号" :trigger-on-focus="false"
            style="width:240px;" :fetch-suggestions="searchProductAsync" :value-key="'productname'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item prop='containername' label="批次号:">
          <el-autocomplete v-model.trim="queryInfo.containername" placeholder="请输入批次号" :trigger-on-focus="false"
            style="width:280px;" :fetch-suggestions="searchContainerAsync" :value-key="'containername'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item label="订单类型:">
          <el-select v-model="queryInfo.ordertype" placeholder="请选择" clearable filterable style="width: 100px;">
            <el-option v-for="i in ordertypeList" :key="i.value" :label="i.value" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="计划类型:">
          <el-select v-model="queryInfo.plantype" placeholder="请选择" clearable filterable style="width: 100px;">
            <el-option v-for="i in plantypeList" :key="i.value" :label="i.value" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间:">
          <el-date-picker v-model="queryInfo.startdate" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间:">
          <el-date-picker v-model="queryInfo.enddate" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
            start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
        </el-form-item>

        <el-form-item label="周计划完成时间:">
          <el-date-picker v-model="queryInfo.weekplanfinishdate" type="daterange" range-separator="至"
            value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="重要等级">
          <el-input v-model.trim="queryInfo.priority" clearable></el-input>
        </el-form-item>

        <el-form-item label="风险程度">
          <el-input v-model.trim="queryInfo.risklevel" clearable></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model.trim="queryInfo.notes" clearable></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="getData">查询</el-button>
          <el-button type="primary" icon="el-icon-download" size="small" @click="getExportExcel">导出</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" @click="orderImport.dialogVisible = true">
            订单分类 导入
          </el-button>
          <el-button type="warning" size="small" icon="el-icon-upload2" @click="weekPlanImport.dialogVisible = true">
            周计划完成时间 导入
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格显示区 -->
      <el-table v-loading="loading" v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" :data="dataList" stripe border>
        <el-table-column type="index" width="50px"></el-table-column>
        <el-table-column label="id" prop="id" width="100" v-if="false"></el-table-column>
        <el-table-column label="零件图号" prop="productname" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="批次号" prop="containername" width="260" show-overflow-tooltip></el-table-column>
        <el-table-column label="订单类型" prop="ordertype" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="计划类型" prop="plantype" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="开始时间" prop="startdate" width="100" :formatter="splitDate"></el-table-column>
        <el-table-column label="结束时间" prop="enddate" width="100" :formatter="splitDate"></el-table-column>
        <el-table-column label="周计划完成时间" prop="weekplanfinishdate" width="120" :formatter="splitDate"></el-table-column>
        <el-table-column label="重要等级" prop="priority" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="风险程度" prop="risklevel" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="备注" prop="notes" show-overflow-tooltip></el-table-column>
        <el-table-column label="导入人" prop="creater" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="导入时间" prop="createdate" width="100" :formatter="splitDate"></el-table-column>
        <el-table-column label="修改人" prop="updater" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="修改时间" prop="lastchangedate" width="100" :formatter="splitDate"></el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[12,50,100]" :page-size="queryInfo.pageSize"
        layout="prev,pager,next,jumper,sizes,total" :total="total">
      </el-pagination>

      <!-- 回到顶部 -->
      <el-backtop></el-backtop>
    </div>

    <!-- 订单分类导入 -->
    <el-dialog title="订单分类导入" :visible.sync="orderImport.dialogVisible" width="90%" :top="'20px'"
      @close="orderImport.dataList = []">
      <el-form :inline="true" ref="orderImportRef">
        <el-form-item>
          <el-upload action="" :before-upload="orderImportBeforeUpload" :multiple="true" accept=".xls,.xlsx">
            <el-button slot="trigger" type="primary" size="small" icon="el-icon-upload">选择文件</el-button>
            <el-button type="success" size="small" icon="el-icon-success" @click="saveOrderImportData">保存</el-button>
            <span style="color:red;font-weight:bold;margin-left: 10px;">内部系统，严禁上传涉密信息</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="orderImport.dataList" stripe border ref="orderImportData" v-loading="loading"
        v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" height="640">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleEdit(scope.$index, scope.row)">
            </el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index, scope.row)">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="校验结果" prop="islegel" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.islegel === 1" type="success">校验成功</el-tag>
            <el-tag v-else type="danger">校验失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="校验失败原因" prop="illegalreason">
          <template slot-scope="scope">
            <span style="color:red;font-weight:bold;" v-if="scope.row.islegel === 0">
              <i class="el-icon-warning"></i>
              {{scope.row.illegalreason}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="唯一id" prop="id" v-if="false"></el-table-column>
        <el-table-column label="批次号" prop="containername" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="订单类型" prop="ordertype" width="80"></el-table-column>
        <el-table-column label="计划类型" prop="plantype" width="80" show-overflow-tooltip></el-table-column>
        <el-table-column label="开始时间" prop="startdate" width="100"></el-table-column>
        <el-table-column label="结束时间" prop="enddate" width="100"></el-table-column>
        <el-table-column label="重要等级" prop="priority" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="风险程度" prop="risklevel" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="备注" prop="notes" width="120" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 修改数据弹窗 -->
    <el-dialog title="修改数据" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose"
      :close-on-click-modal="true">
      <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" :inline="true" :label-position="'top'"
        lable-width="100px">
        <el-form-item label="批次号" prop="containername">
          <el-input v-model="editForm.containername"></el-input>
        </el-form-item>

        <el-form-item label="订单类型" prop="ordertype">
          <el-select v-model="editForm.ordertype" palaceholder="请选择" filterable clearable>
            <el-option v-for="i in ordertypeList" :key="i.value" :label="i.label" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="计划类型" prop="plantype">
          <el-select v-model="editForm.plantype" palaceholder="请选择" filterable clearable>
            <el-option v-for="i in plantypeList" :key="i.value" :label="i.label" :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startdate">
          <el-date-picker v-model="editForm.startdate" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="enddate">
          <el-date-picker v-model="editForm.enddate" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="重要等级">
          <el-input v-model="editForm.priority"></el-input>
        </el-form-item>

        <el-form-item label="风险程度">
          <el-input v-model="editForm.risklevel"></el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="editForm.notes" style="width: 600px;"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹出窗底下按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveChangedRowData" size="small">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 周计划导入 -->
    <el-dialog title="周计划完成时间导入" :visible.sync="weekPlanImport.dialogVisible" width="60%" :top="'20px'"
      @close="weekPlanImport.dataList = []">
      <el-form :inline="true" ref="weekPlanImportRef">
        <el-form-item>
          <el-upload action="" :before-upload="weekPlanImportBeforeUpload" :multiple="true" accept=".xls,.xlsx">
            <el-button slot="trigger" type="primary" size="small" icon="el-icon-upload">选择文件</el-button>
            <el-button type="success" size="small" icon="el-icon-success" @click="saveWeekPlanImportData">保存
            </el-button>
            <span style="color:red;font-weight:bold;margin-left: 10px;">内部系统，严禁上传涉密信息</span>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-table :data="weekPlanImport.dataList" stripe border ref="weekPlanImportTable" v-loading="loading"
        v-loading.fullscreen.lock="loading" :element-loading-text="loadingText"
        element-loading-background="rgba(0,0,0,0.8)" height="640">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-delete" type="danger"
              @click="handleWeekPlanImportDataDelete(scope.$index, scope.row)">
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="校验结果" prop="islegel" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.islegel === 1" type="success">校验成功</el-tag>
            <el-tag v-else type="danger">校验失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="校验失败原因" prop="illegalreason" width="250" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="color:red;font-weight:bold;" v-if="scope.row.islegel === 0">
              <i class="el-icon-warning"></i>
              {{scope.row.illegalreason}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="唯一id" prop="id" v-if="false"></el-table-column>
        <el-table-column label="批次号" prop="containername" show-overflow-tooltip></el-table-column>
        <el-table-column label="周计划完成时间" prop="weekplanfinishdate" width="160"></el-table-column>
      </el-table>
    </el-dialog>
  </div>

  <script src="../Scripts/echarts/echarts-5.4.0.min.js"></script>
  <script type="module">
    import { fetchSuggestion, exportExcelData } from '../Scripts/hooks/useCommonMethod.js'
    import { getParams, getUserWhiteList, generateUUID } from '../Scripts/hooks/useCommonMethod.js'
    import { prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth } from '../Scripts/hooks/useDateShortCut.js'
    import { splitDate, replaceDate } from '../Scripts/hooks/format.js'
    import Vue2ReportHeader from '../Scripts/components/Vue2ReportHeader.js';
    const app = new Vue({
      el: '#app',
      components: { Vue2ReportHeader },
      data: {
        splitDate, replaceDate,
        loading: false,
        loadingText: '数据加载中...',
        queryInfo: {
          productname: '', containername: '', ordertype: '', plantype: '', startdate: '', enddate: '',
          weekplanfinishdate: '', priority: '', risklevel: '', notes: '', currentPage: 1, pageSize: 12
        },
        total: 0,
        formDisable: false,
        factoryname: '',
        dataList: [],
        ordertypeList: [{ lable: '临时', value: '临时' }, { lable: '品种', value: '品种' }, { lable: '预品种', value: '预品种' }],
        plantypeList: [{ lable: '初制', value: '初制' }, { lable: '复制', value: '复制' }, { lable: '修理', value: '修理' }],
        pickerOptions: { shortcuts: [prevWeek, thisWeek, nextWeek, prevMonth, thisMonth, nextMonth] },
        editDialogVisible: false,
        editFormRule: {
          containername: [{ required: true, message: '批次号不能为空', trigger: 'blur' }],
          ordertype: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
          plantype: [{ required: true, message: '计划类型不能为空', trigger: 'change' }],
          startdate: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
          enddate: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
        },
        editForm: { containername: '', ordertype: '', plantype: '', startdate: '', enddate: '', notes: '', priority: '', risklevel: '', selectRowIndex: 0 },
        // excel模板表头
        excelTemplateHeader: {
          containername: '批次号', ordertype: '订单类型', plantype: '计划类型', startdate: '开始时间', enddate: '结束时间',
          notes: '备注', priority: '重要等级', risklevel: '风险程度'
        },
        // 订单分类导入
        orderImport: { dialogVisible: false, dataList: [] },
        // 周计划完成时间导入
        weekPlanImport: { dialogVisible: false, dataList: [] }
      },
      methods: {
        // 查询件号
        searchProductAsync(value, callback) {
          fetchSuggestion({ actionName: 'getProductnameAsync', name: 'productname', value, callback })
        },
        // 查询批次号
        searchContainerAsync(value, callback) {
          fetchSuggestion({ actionName: 'getContainernameAsync', name: 'containername', value, callback })
        },
        async getData() {
          this.loading = true;
          this.loadingText = '数据加载中...';
          const { data: { data, meta, total } } = await axios.post('../handler/report/GZOrderTypeImportReport.ashx?action=getData', {
            type: 'getData',
            ...this.queryInfo
          })
          this.loading = false;
          if (meta.status === 500) { return this.$message.error(meta.msg); }
          this.dataList = data;
          this.total = total;
        },
        // 导出excel
        async getExportExcel() {
          this.$refs['queryInfoRef'].validate(async (valid) => {
            if (!valid) {
              return this.$message.error('必填项不能为空');
            } else {
              const config = {
                url: '../handler/report/GZOrderTypeImportReport.ashx?action=exportExcel',
                data: { type: 'exportExcel', ...this.queryInfo }
              }
              exportExcelData(config, this);
            }
          })
        },
        async getFactoryInfo() {
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/CommonActionHandle.ashx?actions=getFactoryInfo',
            method: 'post',
            data: { type: 'getFactoryInfo', factoryid: Decrypt(getParams('factoryid')), isMapping: '是' }
          })
          const { factoryid, factoryname } = data[0];
          this.factoryname = factoryname;
          document.title = factoryname + '订单分类导入';
        },
        // 【订单导入】文件加载后
        orderImportBeforeUpload(file) {
          let reader = new FileReader();
          reader.onload = e => {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, { type: 'array' });
            let first_sheet_name = workbook.SheetNames[0];
            let worksheet = workbook.Sheets[first_sheet_name];
            let content = XLSX.utils.sheet_to_json(worksheet, { raw: false, defval: null });
            if (content.length === 0) {
              return this.$message.error('所导入的excel文件为空');
            }
            // 检验excel模板是否缺少列
            if (this.hasExcelMissingColumn(content[0])) { return; }
            let returnData = [];
            for (const i of content) {
              let item = {
                containername: i["批次号"],
                ordertype: i["订单类型"],
                plantype: i["计划类型"],
                startdate: i["开始时间"] ? dayjs(i["开始时间"]).format('YYYY-MM-DD') : '',
                enddate: i["结束时间"] ? dayjs(i["结束时间"]).format('YYYY-MM-DD') : '',
                notes: i["备注"],
                priority: i["重要等级"],
                risklevel: i["风险程度"],
                islegel: 1,//默认校验成功
                illegalreason: '',//默认失败原因为空
                id: generateUUID() //生成唯一id
              }
              returnData.push(item);
            }
            this.orderImport.dataList = this.validateEachRowData(returnData);
          };
          reader.readAsArrayBuffer(file);
          return false;
        },
        // 检验excel模板是否缺少列
        hasExcelMissingColumn(data) {
          return Object.values(this.excelTemplateHeader).some(i => {
            if (!(i in data)) {
              this.$message.error(`所导入的excel文件缺少【${i}】列`);
              return true;
            }
          })
        },
        // 校验所导入excel数据
        validateEachRowData(returnData) {
          for (const i of returnData) {
            if (!i.containername) {
              i.islegel = 0;
              i.illegalreason = '批次号不能为空';
            }
            if (!i.ordertype) {
              i.islegel = 0;
              i.illegalreason = '订单类型不能为空';
            } else {
              if (!(i.ordertype === '临时' || i.ordertype === '品种' || i.ordertype === '预品种')) {
                i.islegel = 0;
                i.illegalreason = '订单类型只能是【临时、品种、预品种】中的一种';
              }
            }
            if (!i.plantype) {
              i.islegel = 0;
              i.illegalreason = '计划类型不能为空';
            } else {
              if (!(i.plantype === '初制' || i.plantype === '复制' || i.plantype === '修理')) {
                i.islegel = 0;
                i.illegalreason = '计划类型只能是【初制、复制、修理】中的一种';
              }
            }
            if (!i.startdate) {
              i.islegel = 0;
              i.illegalreason = '开始时间不能为空';
            } else {
              if (i.startdate === 'Invalid Date') {
                i.islegel = 0;
                i.illegalreason = '开始时间不是有效的日期格式';
              }
            }
            if (!i.enddate) {
              i.islegel = 0;
              i.illegalreason = '结束时间不能为空';
            } else {
              if (i.enddate === 'Invalid Date') {
                i.islegel = 0;
                i.illegalreason = '结束时间不是有效的日期格式';
              }
            }
          }
          return returnData;
        },
        // 校验用户权限
        async validateUser() {
          if (!getParams('uid')) {
            this.formDisable = true;
            return this.$notify.error({ title: '错误', message: '缺少用户信息!', duration: 0 });
          }
          const employeeid = getParams("uid");
          // 获取用户权限白名单
          const pageurl = window.location.pathname.split('/')[3];
          const whiteList = await getUserWhiteList(pageurl, this.$message);
          if (whiteList.indexOf(employeeid) == -1) {
            this.formDisable = true;
            this.$message.error('当前用户无权使用该功能');
          }
        },
        // 移除所选行
        async handleDelete(index, row) {
          const confirmResult = await this.$confirm('删除该行数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }
          this.orderImport.dataList.splice(index, 1);
        },
        // 修改所选数据
        handleEdit(index, row) {
          this.editDialogVisible = true;
          this.editForm = {
            ...row,
            ordertype: this.ordertypeList.some(i => i.value === row.ordertype) ? row.ordertype : '',
            plantype: this.plantypeList.some(i => i.value === row.plantype) ? row.plantype : ''
          }
          this.editForm.selectRowIndex = index;
        },
        // 保存被修改的行数据
        saveChangedRowData(row) {
          this.$refs["editFormRef"].validate(async (valid) => {
            if (!valid) {
              this.$message.error('必填项不能为空');
            } else {
              this.$message.success('修改成功');
              const index = this.editForm.selectRowIndex;
              this.$set(this.orderImport.dataList, index, { ...this.editForm, islegel: 1, illegalreason: '' });
              this.editDialogVisible = false;
            }
          })
        },
        // 修改对话框关闭后
        editDialogClose() {
          this.$refs["editFormRef"].resetFields();
        },
        // 【订单导入】保存前校验
        async validate() {
          const selection = this.$refs.orderImportData.selection;
          this.loading = true;
          this.loadingText = '数据校验中...';
          const { data: { data, meta, total } } = await axios({
            method: 'POST',
            url: '../handler/report/GZOrderTypeImportReport.ashx?action=validate',
            data: { type: 'validate', toValidateData: selection }
          })
          this.loading = false;
          if (meta.status === 500) { return this.$message.error(meta.msg); }
          for (const item of data) {
            this.orderImport.dataList.forEach((i, index) => {
              if (item.id === i.id) {
                this.$set(this.orderImport.dataList[index], "islegel", item.islegel);
                this.$set(this.orderImport.dataList[index], "illegalreason", item.illegalreason);
              }
            })
          }
          return total > 0 ? false : true;
        },
        // 保存【订单分类】导入数据
        async saveOrderImportData() {
          const selection = this.$refs.orderImportData.selection;
          if (selection.length === 0) {
            return this.$message.error('请选择待保存的数据');
          }
          if (selection.some(i => i.islegel === 0)) {
            return this.$message.error('所选数据中存在校验失败的行！请修改校验失败的数据至正确、或将校验失败的数据删除后重试!');
          }
          // 保存前先校验批次号是否存在
          const validateResult = await this.validate();
          if (!validateResult) {
            return this.$message.error('校验失败，请修改校验失败的数据至正确、或将校验失败的数据删除后重试!');
          } else {
            this.loading = true;
            this.loadingText = '数据保存中...';
            const { data: { data, meta, total } } = await axios({
              method: 'POST',
              url: '../handler/report/GZOrderTypeImportReport.ashx?action=saveOrderImportData',
              data: { type: 'saveOrderImportData', willBeSavedData: selection, employeeid: getParams("uid") }
            })
            this.loading = false;
            if (meta.status === 500) { return this.$message.error(meta.msg); }
            this.$message.success('保存成功');
            this.orderImport.dataList = [];
            this.getData();
          }
        },
        // 【周计划完成时间】文件加载后
        weekPlanImportBeforeUpload(file) {
          let reader = new FileReader();
          reader.onload = e => {
            let data = new Uint8Array(e.target.result);
            let workbook = XLSX.read(data, { type: 'array' });
            let first_sheet_name = workbook.SheetNames[0];
            let worksheet = workbook.Sheets[first_sheet_name];
            let content = XLSX.utils.sheet_to_json(worksheet, { raw: false, defval: null });
            if (content.length === 0) { return this.$message.error('所导入的excel文件为空'); }
            // 检验excel模板是否缺少列
            const weekplanExcelTemplateHeader = { containername: '批次号', weekplanfinishdate: '周计划完成时间' };
            Object.values(weekplanExcelTemplateHeader).some(i => {
              if (!(i in content[0])) { return this.$message.error(`所导入的excel文件缺少【${i}】列`); }
            })
            let returnData = [];
            for (const i of content) {
              let item = {
                containername: i["批次号"],
                weekplanfinishdate: i["周计划完成时间"] ? dayjs(i["周计划完成时间"]).format('YYYY-MM-DD') : '',
                islegel: 1,//默认校验成功
                illegalreason: '',//默认失败原因为空
                id: generateUUID() //生成唯一id
              }
              returnData.push(item);
            }

            for (const i of returnData) {
              if (!i.containername) {
                i.islegel = 0;
                i.illegalreason = '批次号不能为空';
              }
              if (!i.weekplanfinishdate) {
                i.islegel = 0;
                i.illegalreason = '周计划完成时间不能为空';
              } else {
                if (i.weekplanfinishdate === 'Invalid Date') {
                  i.islegel = 0;
                  i.illegalreason = '周计划完成时间不是有效的日期格式';
                }
              }
            }
            this.weekPlanImport.dataList = returnData;
          };
          reader.readAsArrayBuffer(file);
          return false;
        },
        // 【周计划完成时间】导入数据删除所选行
        async handleWeekPlanImportDataDelete(index, row) {
          const confirmResult = await this.$confirm('删除该行数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err)
          if (confirmResult !== 'confirm') { return this.$message.info('已取消删除!'); }
          this.weekPlanImport.dataList.splice(index, 1);
        },
        // 保存【周计划完成时间】导入数据
        async saveWeekPlanImportData() {
          const selection = this.$refs.weekPlanImportTable.selection;
          if (selection.length === 0) {
            return this.$message.error('请选择待保存的数据');
          }
          if (selection.some(i => i.islegel === 0)) {
            return this.$message.error('所选数据中存在校验失败的行！请修改校验失败的数据至正确、或将校验失败的数据删除后重试!');
          }
          // 保存前先校验批次号是否存在
          const validateResult = await this.weekPlanImportValidate();
          if (!validateResult) {
            return this.$message.error('校验失败，请修改校验失败的数据至正确、或将校验失败的数据删除后重试!');
          } else {
            this.loading = true;
            this.loadingText = '数据保存中...';
            const { data: { data, meta, total } } = await axios({
              method: 'POST',
              url: '../handler/report/GZOrderTypeImportReport.ashx?action=saveWeekPlanImportData',
              data: { type: 'saveWeekPlanImportData', willBeSavedData: selection, employeeid: getParams("uid") }
            })
            this.loading = false;
            if (meta.status === 500) { return this.$message.error(meta.msg); }
            this.$message.success('保存成功');
            this.weekPlanImport.dataList = [];
            this.getData();
          }
        },
        // 【周计划完成时间】保存前校验
        async weekPlanImportValidate() {
          const selection = this.$refs.weekPlanImportTable.selection;
          this.loading = true;
          this.loadingText = '数据校验中...';
          const { data: { data, meta, total } } = await axios({
            method: 'POST',
            url: '../handler/report/GZOrderTypeImportReport.ashx?action=weekPlanImportValidate',
            data: { type: 'weekPlanImportValidate', toValidateData: selection }
          })
          this.loading = false;
          if (meta.status === 500) { return this.$message.error(meta.msg); }
          for (const item of data) {
            this.weekPlanImport.dataList.forEach((i, index) => {
              if (item.id === i.id) {
                this.$set(this.weekPlanImport.dataList[index], "islegel", item.islegel);
                this.$set(this.weekPlanImport.dataList[index], "illegalreason", item.illegalreason);
              }
            })
          }
          return total > 0 ? false : true;
        },
        handleCurrentChange(newPage) {
          this.queryInfo.currentPage = newPage;
          this.getData();
        },
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          this.getData();
        }
      },
      mounted() {
        this.getFactoryInfo();
        this.validateUser();
      },
      watch: { queryInfo: { handler() { this.queryInfo.currentPage = 1 }, deep: true } }
    })
  </script>
</body>

</html>